# coding=utf-8
# author:xc
# datetime:2018/10/23 10:08

from . import api
from flask import request
from dbConnection.MysqlConn import Mysql
from app import util
from app.MySession import MySession


# 获取验证
@api.route('/api/news/code', methods=['POST', 'GET'])
def api_news_code():
    phone = request.values.get('phone')
    flag = request.values.get('flag', default=0)
    if int(flag) == 0:  # 注册
        mysql = Mysql()
        is_exist = mysql.getOne("select * from news_user where phone='%s'" % phone, None)
        if is_exist:
            code = util.CODE_EXIST
            msg = u'该手机已经被注册'
        else:
            sms_id = 147675
            code = util.jg_send_sms(phone, sms_id)
            msg = u'验证码发送成功'
        mysql.dispose()
    elif int(flag) == 1:
        mysql = Mysql()
        is_exist = mysql.getOne("select * from news_user where phone='%s'" % phone, None)
        if is_exist:
            sms_id = 147675
            code = util.jg_send_sms(phone, sms_id)
            msg = u'验证码发送成功'
        else:
            code = util.CODE_FAIL
            msg = u'该手机未被注册'
    data = {
        'code': code,
        'msg': msg
    }
    return util.to_json(data)


# 注册
@api.route('/api/news/register', methods=['POST', 'GET'])
def api_news_register():
    phone = request.values.get('phone')
    code = request.values.get('code')
    is_verify = util.verify_code(phone, code)
    if is_verify != util.CODE_SUCCESS:
        data = {
            'code': util.CODE_FAIL,
            'msg': u"验证码不正确"
        }
        return util.to_json(data)
    password = request.values.get("password")
    mysql = Mysql()
    is_exist = mysql.getOne("select * from news_user where phone='%s'" % phone, None)
    if is_exist is None:
        sql = "INSERT INTO news_user (phone,password,registerTime,ip)" \
              " values ('%s','%s',now(),'%s')" % (
                  phone, util.md5(str(password) + util.LOGIN_KEY), util.get_current_ip())
        result = mysql.insertOne(sql, None)
        if result > 0:
            code = util.CODE_SUCCESS
            msg = u'注册成功'
        else:
            code = util.CODE_FAIL
            msg = u'注册失败'
    else:
        code = util.CODE_EXIST
        msg = u'账号已存在'
    mysql.dispose()
    data = {
        'code': code,
        'msg': msg
    }
    return util.to_json(data)


# 用户登录
@api.route('/api/news/login', methods=['POST', 'GET'])
def api_user_login():
    phone = request.values.get("phone")
    password = request.values.get("password")
    mysql = Mysql()
    sql = "SELECT * FROM news_user WHERE phone = '%s' AND password = '%s'" % (
        phone, util.md5(str(password) + util.LOGIN_KEY))
    result = mysql.getOne(sql, None)
    if result is not None:
        if result["status"] == 1:
            code = util.CODE_SUCCESS
            msg = u'登录成功'
            update_sql = "UPDATE news_user SET loginNum = loginNum + 1 , " \
                         "loginTime = now(),loginIp ='%s' WHERE uid = '%s' " % (util.get_current_ip(), result["uid"])
            mysql.update(update_sql, None)

            session = MySession.create_session(str(result["uid"]))
        else:
            code = util.CODE_FAIL
            msg = u'登录失败'
            session = ""

    else:
        code = util.CODE_FAIL
        session = ""
        msg = u'登录失败'
        result = {}
    data = {
        'code': code,
        'session': session,
        'msg': msg,
        'result': result
    }
    return util.to_json(data)


# 修改密码
@api.route('/api/news/update_password', methods=['POST', 'GET'])
@util.verify_login
def api_new_update_password(uid):
    try:
        oldpassword = request.values.get('oldpassword')
        newpassword = request.values.get('newpassword')
        sql = "select * from news_user where password='%' and uid='%s'" % (
            util.md5(str(oldpassword) + util.LOGIN_KEY), uid)
        mysql = Mysql()
        is_exist = mysql.getOne(sql, None)
        if is_exist is not None:
            sql1 = "update news_user set password='%s' where uid='%s'" % (
                util.md5(str(newpassword) + util.LOGIN_KEY), uid)
            mysql.update(sql1, None)
            code = util.CODE_SUCCESS
            msg = u'修改密码成功'
        else:
            code = util.CODE_FAIL
            msg = u'原密码输入错误'
    except Exception as e:
        print e
        code = util.CODE_ERROR
        msg = u'服务器内部错误'
    data = {
        'code': code,
        'msg': msg
    }
    return util.to_json(data)


# 忘记密码
@api.route('/api/news/forgot_password', methods=['POST', 'GET'])
def api_news_forgot_password():
    try:
        phone = request.values.get('phone')
        code = request.values.get('code')
        is_verify = util.verify_code(phone, code)
        if is_verify != util.CODE_SUCCESS:
            data = {
                'code': util.CODE_FAIL,
                'msg': u"验证码不正确"
            }
            return util.to_json(data)
        password = request.values.get("password")
        mysql = Mysql()
        sql = "update news_user set password='%s' where phone='%s'" % (util.md5(str(password) + util.LOGIN_KEY), phone)
        res = mysql.update(sql, None)
        mysql.dispose()
        if res > 0:
            code = util.CODE_SUCCESS
            msg = u'重置密码成功'
    except Exception as e:
        print e
        code = util.CODE_ERROR
        msg = u'服务器内部错误'
    data = {
        'code': code,
        'msg': msg
    }
    return util.to_json(data)
